package com.baiytfp.hf.HFDataExchange.action.dao;

import com.baiytfp.hf.HFDataExchange.common.model.base.TableName;
import com.baiytfp.hf.HFDataExchange.common.model.state.TreeType;
import com.baiytfp.hf.HFDataExchange.common.model.table.Func;
import com.baiytfp.hf.baiytfp.hfutils.HFDBHelper;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class FuncDAOImpl {
		
	// 读取树 ( 只返回树数据，让前台自己组装 ) (先从子结点读起，适合组装成树)
		public List<Map> getTree(String treeType,  String parentTreeCode)
				throws Exception {
			StringBuffer sWhere = new StringBuffer();
			List params = new ArrayList();
			StringBuffer sql = new StringBuffer();
			sql.append("select t1.*,attr.func_code, attr.func_name, attr.func_content, attr.func_note from ");
			sql.append(TableName.TREE + " t1 left join ");
			sql.append(TableName.FUNC + " attr on t1.id=attr.tree_id ");

			if (sWhere.length() > 0) {
				sWhere.append(" and ");
			}
			sWhere.append(" TREE_TYPE=? and (IS_OPEN=1 OR IS_OPEN IS NULL) ");
			params.add(treeType);

			if (!"".equals(parentTreeCode)) {
				sWhere.append(" and tree_code like ? ");
				params.add(parentTreeCode + "%");
			}
			// String orderBy =
			// " order by node_deep desc, parent_seq_code, node_order asc "; //
			// 先把父结点取出来
			String orderBy = " order by node_deep asc, parent_tree_code, node_order asc "; // 先把父结点取出来
			List<Map> list = HFDBHelper.querySql(sql + " where " + sWhere.toString() + orderBy, Map.class, params.toArray());
			return list;
		}
		
		public Func getFuncInfoByTreeCode(String treeCode) throws Exception {
			Func func= HFDBHelper.read(TableName.FUNC, " t where exists (select id from " + TableName.TREE + " where id=t.tree_id and tree_type=? and tree_code = ? ) ",
					Func.class, new Object[] { TreeType.MANAGE_FUNC.getKey() , treeCode } );
			return func;
		}

		public Func update(String treeId,Map funcParam) throws Exception {
			Func func = HFDBHelper.read(TableName.FUNC, " where tree_id=? ", Func.class, treeId);
			BeanUtils.populate(func, funcParam);
			long rs = HFDBHelper.update(TableName.FUNC, " where tree_id=? ", func, func.getTree_id());
			return rs>0? func : null;
		}
		
		
		public Func add(Func func) throws Exception {
			long  rs = HFDBHelper.add(TableName.FUNC, func);
			return rs>0?func:null;
		}
		
		
		public boolean delByTreeCode(String treeCode) throws Exception {
			long rs = HFDBHelper.delete(TableName.FUNC, "where exists (select id from " + TableName.TREE + " where id=hfdataexchange_func.tree_id and tree_code like ? ) ", treeCode + "%");
			return rs >= 0;
		}

		public List<Map> listFuncForRight(String treeType, String objCode, String objType) throws Exception {
			// TODO Auto-generated method stub
			return null;
		}
		
	
}
